<template>
  <div class="upload-container">
    <el-upload
      action="/api/upload"
      :headers="headers"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :show-file-list="false"
      accept="image/*"
    >
      <el-button type="primary">上传图片</el-button>
      <template #tip>
        <div class="el-upload__tip">支持JPG/PNG格式，大小不超过5MB</div>
      </template>
    </el-upload>
    
    <el-image
      v-if="imageUrl"
      :src="imageUrl"
      fit="cover"
      class="preview-image"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user.js'

const userStore = useUserStore()
const imageUrl = ref('')

const headers = {
  Authorization: `Bearer ${userStore.token}`
}

const beforeUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式图片!')
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
  }
  return isImage && isLt5M
}

const handleSuccess = (response) => {
  if (response.success) {
    imageUrl.value = response.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.error || '上传失败')
  }
}

const handleError = () => {
  ElMessage.error('上传失败，请重试')
}
</script>

<style scoped>
.upload-container {
  margin: 20px 0;
}
.preview-image {
  margin-top: 20px;
  max-width: 100%;
  max-height: 400px;
}
</style>